<?php
namespace Mobile\Model;
use Think\Model;
/**
 * 会员模型 
 */
class MemberModel extends Model
{
   private static $obj;
   
   protected $tablePrefix      =   'vip_';
   /**
    *  推荐人是否存在
    */
   public function getTj($tjId)
   {
       //找到推荐人的id 如果没有,不允许注册.
       return  $this->where(''.$this->getPk().'="'.$tjId.'"')->getField('path');
   }
   
   public static function getInitnation()
   {
       $name = __CLASS__;
       return self::$obj = !(self::$obj instanceof $name) ? new self() : self::$obj;
   }
   
   public function add($data = '', $options = array(), $replace = false)
   {
       if (empty($data) || !is_array($data))
       {
           return array();
       }
       $data['card_id']     = $data['idcard'];
       $data['pid']         = $data['id'];
       $data['true_name']   = $data['realname'];
       $data['grade_name']  = '会员';
       unset($data['idcard'], $data['id'], $data['realname']);
       $data = $this->create($data);
       return parent::add($data, $options, $replace);
   }
   
   protected function _before_insert(& $data, $options)
   {
       $data['create_time'] = time();
       $data['status']      = 1;
       return $data;
   }
   
   //更新层级关系
   public function save($data,  $options)
   {
        if (empty($data))
        {
            return false;
        }
        $path=$data.$options['childrenId'];
        $isSuccess = parent::save(array(
            'path'      => $path,
        ), array('where' => array('id' => $options['childrenId'])));
        return $isSuccess;
   }
   
   /**
    * 登录
    */
   public function login(array $data)
   {
       if (empty($data))
       {
           return array();
       }
   
       foreach ($this->checkKey as $name)
       {
           if (!array_key_exists($name, $data))
           {
               return array();
           }
       }
        
       $isSuccess = $this->field('true_name as username,id')
        -> where('mobile ="%s" AND password = "%s"', array($data['mobile'],$data['password']))
        -> find();
       if (empty($isSuccess))
       {
           return false;
       }
       $_SESSION['userId'] =  $isSuccess['id'];
       unset($isSuccess['id']);
       return !empty($isSuccess)  ? $isSuccess :$_SESSION['userId'];
   }
   
   public function getUserInfoById()
   {
       return $this->field('grade_name, true_name')->where('user_id = "%s"', $_SESSION['userId'])->find();
   }
}